// 无缓冲 channel 具有同步特性，这让它在某些场合可以替代锁，让程序更加清晰，可读性也更好。
// 首先看一个传统的、基于“共享内存”+“互斥锁”的 Goroutine 安全的计数器的实现:
// 使用了一个带有互斥锁保护的全局变量作为计数器，所有要操作计数器的 Goroutine 共享这个全局变量，并在互斥锁的同步下对计数器进行自增操作。
package main

import (
	"fmt"
	"sync"
)

type counter struct {
	sync.Mutex
	i int
}

var cter counter

func Increase() int {
	cter.Lock()
	defer cter.Unlock()
	cter.i++
	return cter.i
}
func main() {
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(i int) {
			v := Increase()
			fmt.Printf("goroutine-%d: current counter value is %d\n", i, v)
			wg.Done()
		}(i)
	}
	wg.Wait()
}

/*
goroutine-9: current counter value is 4
goroutine-0: current counter value is 1
goroutine-5: current counter value is 6
goroutine-7: current counter value is 7
goroutine-6: current counter value is 9
goroutine-2: current counter value is 10
goroutine-4: current counter value is 5
goroutine-1: current counter value is 2
goroutine-3: current counter value is 3
goroutine-8: current counter value is 8
*/
